package com.tstudy.laoshibang.base;


import java.util.ArrayList;

import org.apache.http.Header;

import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.tencent.connect.common.Constants;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.login.NeedLoginFragment;
import com.tstudy.laoshibang.manager.GroupManager;
import com.tstudy.laoshibang.manager.UserManager;
import com.tstudy.laoshibang.mode.TGroup;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.share.WrapQQ;
import com.tstudy.laoshibang.share.WrapSinaWeibo;
import com.tstudy.laoshibang.utils.AppShortCutUtil;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.utils.SharedPreferencesUtil;
import com.tstudy.laoshibang.utils.ViewServer;
import com.umeng.analytics.MobclickAgent;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Window;
/**
 * Activity 基类
* @CopyRight weitaming.com
* @author wuyahui
* @E-mail wuyahui@ispied.com
* @version 1.0.0
* @Date 2014年4月29日 下午5:02:53
 */
public abstract class BaseActivity extends FragmentActivity{
	FragmentManager mFragmentManager;
	Fragment mTabCurrentFragment;
	public int mRootFragmentId;
	public int mRootId;
	public ArrayList <Fragment> mFragmentStack = new ArrayList<Fragment>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mFragmentManager = getSupportFragmentManager();
		BaseApplication.addStack(this);
		LogUtil.d("--onCrete::" + this);
		initArgs();
		ViewServer.get(this).addWindow(this); 
	}
	
	public  Fragment getFragmentByTag(String tag){
		return mFragmentManager.findFragmentByTag(tag);
	}
	
	
	/**
	 * 添加fragment
	 * @param containerViewId
	 * @param newFragment
	 * @param tag
	 */
	public void add(int containerViewId,Fragment newFragment,String tag){
		add(containerViewId, newFragment, tag,true);
	}
	
	/**
	 * 添加fragment
	 * @param containerViewId
	 * @param newFragment
	 * @param tag
	 * @param isAnimation
	 */
	public void add(int containerViewId,Fragment newFragment,String tag,boolean isAnimation){
		LogUtil.d("add Activity==" + this + "fragment==" + newFragment);
		FragmentTransaction ft = mFragmentManager.beginTransaction();
//		if(this instanceof IndexActivity){
//			((IndexActivity)this).showTabLayout(false);
//		}
		if(newFragment instanceof NeedLoginFragment && !BaseApplication.checkLogin()){
			//goto login pageon
//			LoginFragment.add(containerViewId, null);
			LoginActivity.show();
			return;
		}else{
			if (isAnimation && mFragmentStack.size() > 0) {
				ft.setCustomAnimations(R.anim.push_in_right,R.anim.push_out_left,R.anim.push_in_left,R.anim.push_out_right);
			}
			ft.replace(containerViewId, newFragment,tag);
			ft.addToBackStack(null);
			mFragmentStack.add(newFragment);
		}
		ft.commit();
	}
	
	/**
	 * 添加tab 中的fragment
	 * @param containerViewId
	 * @param newFragment
	 * @param tag
	 */
	public void addInTab(int containerViewId,Fragment newFragment,String tag){
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		LogUtil.d("addInTab newFragment==" + newFragment);
		if(newFragment instanceof NeedLoginFragment && !BaseApplication.checkLogin()){
//			LoginFragment.add(containerViewId, null);
			LoginActivity.show();
			return;
		}else{
//			ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
			LogUtil.d("addInTab isDetached==" + newFragment.isDetached());
			LogUtil.d("addInTab isRemoving==" + newFragment.isRemoving());
			LogUtil.d("addInTab isAdded==" + newFragment.isAdded());
			if(newFragment.isDetached() && !newFragment.isRemoving()){//加isRemoveing的判断解�?�?��后再进入myprofile黑屏问题
				ft.attach(newFragment);
				LogUtil.d("addInTab mTabCurrentFragment==" + mTabCurrentFragment);
			}else{
				if(!newFragment.isAdded()){
					ft.add(mRootFragmentId, newFragment,tag);
				}
				LogUtil.d("addInTab add isAdded==" + newFragment.isAdded());
			}
			if(mTabCurrentFragment != null){
				ft.detach(mTabCurrentFragment);
			}
			mTabCurrentFragment = newFragment;
		}
		ft.commit();
		LogUtil.d("addInTab commit isAdded==" + newFragment.isAdded());
	}
	
	/**
	 * 返回 删除fragment
	 * @param containerViewId
	 * @param fragment
	 */
	public void remove(int containerViewId,Fragment fragment){
		mFragmentManager.popBackStack();
		mFragmentStack.remove(fragment);
		LogUtil.d("--stack count==" + mFragmentManager.getBackStackEntryCount() + "--mTabCurrentFragment==" + mTabCurrentFragment);
		if(mFragmentManager.getBackStackEntryCount() == 1){
			if(this instanceof IndexActivity){
//				if(mTabCurrentFragment instanceof BrowseFragment && ((BrowseFragment) mTabCurrentFragment).mCurrentType == BrowseFragment.BROWSE_TYPE_INDEX_MAP){
//					((IndexActivity)this).showTabLayout(false);
//				}else{
//					((IndexActivity)this).showTabLayout(true);
//				}
			}else{
				if (mFragmentStack.size() == 0) {//其他activety返回退出
					finish();
//					this.overridePendingTransition(R.anim.push_in_right,R.anim.push_out_right);
				}
			}
		}
	}
	
	public BaseFragment getTopFragment(){
		if (mFragmentStack != null && mFragmentStack.size() > 0) {
			return (BaseFragment)mFragmentStack.get(mFragmentStack.size() -1);
		}
		return null;
	}
	
	public abstract class BaseJsonHandler<T> extends BaseJsonHttpResponseHandler<T> {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, T response) {
        	 if (CommonUtil.checkUser((BaseResponse)response)) {
             	if (BaseApplication.checkLogin()) {
             		logout();
 				}else{
 					LoginActivity.show();
 				}
 			}
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, T errorResponse) {
//            BaseApplication.showToast(rawJsonData);
            BaseApplication.showToast("数据请求异常");
        }

        @Override
        public void onStart() {
            super.onStart();
            LogUtil.d("onStart showloading::" + this);
//            showLoadingProgressDialog();
        }
    }
	
//	public void clearFragment(int containerViewId){
//		int size = mFragmentStack.size();
//		for (int i = 0; i < size; i++) {
//			remove(containerViewId, mFragmentStack.get(i));
//		}
//	}
	
	/**
	 * logout注销系统
	 */
	public void logout() {
		UserManager.getInstance().logoutAction(BaseApplication.mUserNo);
		GroupManager.getInstance().clear(TGroup.class);
		AppShortCutUtil.deleteShortCut(BaseApplication.mContext, SplashActivity.class);
		finish();
		clearCache();
		IndexActivity.show(false,false);
//		PushManager.stopWork(BaseApplication.mContext);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtil.d("--BaseActivity requestCode==" + requestCode + "--resultCode==" + resultCode + "this::" + this);
		super.onActivityResult(requestCode, resultCode, data);//进入 fragment的onActivityResult()方法
		LogUtil.d("--BaseActivity after super requestCode==" + requestCode + "--resultCode==" + resultCode + "this::" + this);
		if (requestCode == CONSTANT.WEIBO_SSO_REQUEST_CODE ) {
			WrapSinaWeibo.getInstance().activityResult(requestCode, resultCode, data);
		}
		if (requestCode == Constants.REQUEST_QQ_SHARE) {
        	if (resultCode == Constants.ACTIVITY_OK) {
        		WrapQQ.getInstance().activityResult(data);
        	}
        } 
	}
	
	/**
	 * 清除缓存
	 */
	public void clearCache(){
		BaseApplication.clear();
		SharedPreferencesUtil.clearAccount();
	}

	@Override
	protected void onStart() {
		LogUtil.d("--onStart::" + this);
		super.onStart();
	}
	@Override
	protected void onResume() {
		LogUtil.d("--onResume::" + this);
		super.onResume();
		MobclickAgent.onResume(this);
//		ViewServer.get(this).setFocusedWindow(this); 
	}
	@Override
	protected void onPause() {
		LogUtil.d("--onPause::" + this);
		super.onPause();
		MobclickAgent.onPause(this);
	}
	@Override
	protected void onStop() {
		LogUtil.d("--onStop::" + this);
		super.onStop();
	}
	@Override
	protected void onDestroy() {
		LogUtil.d("--onDestroy::" + this);
		clear();
		BaseApplication.removeStack(this);
		super.onDestroy();
		ViewServer.get(this).removeWindow(this); 
	}
	public abstract void initArgs();
	public abstract void clear();
}
